package lium.lbs.lbsim.activity

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import com.buz.hjcdriver.bean.GetUserInfoResultBean
import lium.lbs.lbsim.utils.UserUtils
import com.lmlibrary.bean.ResponseBean
import lium.lbs.lbsim.utils.callbck.JsonCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_set.*
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.builder.TimePickerBuilder
import java.util.*
import com.bigkoo.pickerview.view.TimePickerView
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.widget.FrameLayout
import com.buz.hjcdriver.bean.AResultBean
import lium.lbs.lbsim.utils.callbck.DialogCallback
import lium.lbs.lbsim.utils.ToastUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import lium.lbs.lbsim.R
import lium.lbs.lbsim.utils.IAlertDialog
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit


class SetActivity : BaseActivity() {
    private var pvTime: TimePickerView? = null
    private var MyMail:String? =null

    override fun getLayoutId(): Int {
        return R.layout.activity_set
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("设置")
        addOnClickListeners(
            R.id.set_renzheng,
            R.id.birthday_choose,
            R.id.birthday_city,
            R.id.set_mibao,
            R.id.change_phone,
            R.id.reset_password,
            R.id.set_clearcache,
            R.id.aboutus,
            R.id.set_email
        )
        initTimePicker()
    }


    override fun onClick(v: View?) {
        super.onClick(v)
        when (v!!.id) {
            R.id.aboutus -> {
                val intent = Intent(this, AboutUsActivity::class.java)
                startActivityForResult(intent, 200)
            }
            R.id.set_renzheng -> {
                val intent = Intent(this, RenZhengActivity::class.java)
                startActivityForResult(intent, 200)
            }
            R.id.birthday_choose -> {
                pvTime?.show()
            }
            R.id.birthday_city -> {
                val intent = Intent(this, ChooseCityActivity::class.java)
                startActivityForResult(intent, 990)
            }
            R.id.set_mibao -> {
                val intent = Intent(this, SetMiBaoActivity::class.java)
                startActivityForResult(intent, 200)
            }
            R.id.change_phone -> {
                val intent = Intent(this, ChangePhoneActivity::class.java)
                startActivityForResult(intent, 200)
            }
            R.id.reset_password -> {
                val intent = Intent(this, RegistActivity::class.java)
                intent.putExtra("isforget", true)
                startActivity(intent)
            }
            R.id.set_clearcache -> {
                clearCache()
            }
            R.id.set_email -> {
                val intent = Intent(this, ChangeEmailActivity::class.java)
                intent.putExtra("email", MyMail)
                startActivityForResult(intent, 200)
            }
        }
    }


    override fun onResume() {
        super.onResume()
        getmyinfo()
    }

    /**初始化开始日期选择器控件 */
    private fun initTimePicker() {
        val selectedDate = Calendar.getInstance()//系统当前时间
        val startDate = Calendar.getInstance()
        startDate.set(1949, 1, 1)
        val endDate = selectedDate
        pvTime = TimePickerBuilder(this, OnTimeSelectListener { date, v ->
            // Toast.makeText(this, getTime(date), Toast.LENGTH_SHORT).show()
            saveUserinfo(getTime(date))
        })
            .setTimeSelectChangeListener { Log.i("pvTime", "onTimeSelectChanged") }
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
            .setRangDate(startDate, endDate)
            .build()

        val mDialog = pvTime!!.dialog
        if (mDialog != null) {
            val params = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                Gravity.BOTTOM
            )
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime!!.dialogContainerLayout.layoutParams = params
            val dialogWindow = mDialog!!.window
            if (dialogWindow != null) {
                dialogWindow!!.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow!!.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
            }
        }
    }

    private fun getTime(date: Date): String {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.time)
        val format = SimpleDateFormat("yyyy/MM/dd")
        return format.format(date)
    }

    private fun saveUserinfo(birthdayStr: String) {
        val param = HashMap<String, String>()
        birthdayStr?.let {
            param["birthday"] = birthdayStr
        }
        postData("/member/updMemberInfo", param, object : DialogCallback<ResponseBean<AResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<AResultBean>>) {
                ToastUtils.showToast(response.body().msg + "")
                getmyinfo()
            }
        })
    }

    private fun getmyinfo() {
        //隐示获取个人信息
        val param = HashMap<String, String>()
        postData("/member/getMemberInfo", param, object : JsonCallback<ResponseBean<GetUserInfoResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<GetUserInfoResultBean>>) {
                UserUtils.login(response.body().data.memberId + "")
                UserUtils.setUserData(
                    response.body().data.uniqueCode,
                    response.body().data.nickName,
                    response.body().data.headImage,
                    response.body().data.phone
                )
                birthday.text = response.body().data.birthday
                city.text = response.body().data.province + " " + response.body().data.city
                phone.text = response.body().data.phone.substring(0, 3) + "****" +
                        response.body().data.phone.substring(8, 11)
                var postion: Int = 0
                postion = response.body().data.email.indexOf("@")
                if (postion >= 7) {
                    email.text = response.body().data.email.substring(0, 2) + "****" +
                            response.body().data.email.substring(postion - 2, response.body().data.email.length)
                } else {
                    email.text = response.body().data.email
                }
                MyMail = response.body().data.email

                if (TextUtils.isEmpty(response.body().data.secretSt1) &&
                    TextUtils.isEmpty(response.body().data.secretSt2) &&
                    TextUtils.isEmpty(response.body().data.secretSt3)
                ) {
                    set_mibao_status.visibility = View.VISIBLE
                } else {
                    set_mibao_status.visibility = View.GONE
                }

                //认证信息  // 实名认证状态 0未认证 1已认证 2认证中 <number>

                when (response.body().data.isVerified) {
                    0 -> {
                        isVerifiedStatus.text = "未认证"
                        isVerifiedStatus.setTextColor(ContextCompat.getColor(this@SetActivity, R.color.color_FF5252))
                        set_renzheng.setOnClickListener(this@SetActivity)
                        isVerifiedStatus.visibility = View.VISIBLE
                    }
                    1 -> {
                        isVerifiedStatus.text = "已认证"
                        isVerifiedStatus.setTextColor(ContextCompat.getColor(this@SetActivity, R.color.color_3D79FE))
                        set_renzheng.setOnClickListener(null)
                        isVerifiedStatus.visibility = View.VISIBLE
                    }
                    2 -> {
                        isVerifiedStatus.text = "认证中"
                        isVerifiedStatus.setTextColor(ContextCompat.getColor(this@SetActivity, R.color.color_FF5252))
                        set_renzheng.setOnClickListener(null)
                        isVerifiedStatus.visibility = View.VISIBLE
                    }
                }

            }
        })
    }


    private fun clearCache() {
        var dialog = IAlertDialog(this, IAlertDialog.LayoutStyle.READALL, Gravity.CENTER)
        dialog.setMessage("确定清除本地缓存？")
        dialog.setPositiveOnClickListener { _, _ ->
            clearCacheNet()
            dialog.dismiss()
        }
        dialog.show()
    }

    private var dialogProgress: ProgressDialog? = null
    private fun clearCacheNet() {
        dialogProgress = ProgressDialog(this)
        dialogProgress?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialogProgress?.setCanceledOnTouchOutside(false)
        dialogProgress?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        dialogProgress?.setMessage("清理中...")
        if (dialogProgress != null && !(dialogProgress?.isShowing!!)) {
            dialogProgress?.show()
        }
        time(2)
    }

    fun time(time: Long) {
        addDisposable(Observable.interval(1, TimeUnit.SECONDS)
            .map { aLong -> time - aLong }
            .take(time + 1)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnComplete {
                dialogProgress?.dismiss()
            }
            .subscribe {
            })
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 200) {
            getmyinfo()
        }
    }

    override fun getNetWorkData() {
    }

}